package com.ky.manage.activity.aftersales;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ky.manage.BaseApplication;
import com.ky.manage.R;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.model.LoginUserInfo;
import com.ky.manage.model.response.AddressDetailResp;
import com.ky.manage.utils.AddressRegionSelectUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

import static com.ky.manage.utils.http.BusinessHttpReqUtils.SERVICE_DOMAIN;

/**
 * 新增/编辑 收货地址
 */
public class AddressDetailActivity extends BaseActivity {

    TextView addressRegionTv;
    EditText name, phone, addressDetail;
    AddressDetailResp resp;

    /**
     * value 0 is add new address, value 1 is modify address
     */
    int type = 0;
    int addressId = -1;
    TextView save;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_address;
    }

    @Override
    protected void initView() {
        findView(R.id.back_iv, v -> {
            finish();
        });
        addressRegionTv = findView(R.id.tv_location);
        addressRegionTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSelectRegion();
            }
        });

        name = findView(R.id.etv_name);
        phone = findView(R.id.etv_phone);
        addressDetail = findView(R.id.etv_address_detail);
        type = getIntent().getIntExtra("type", 0);
        if(type == 0) {
            findTextView(R.id.page_title_tv, "新增收货地址");
        } else {
            findTextView(R.id.page_title_tv, "编辑收货地址");
            addressId = getIntent().getIntExtra("addId", -1);
            getAddressInfoById();
        }

        save = findView(R.id.tv_save);
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(type == 0) {
                    //新增收货地址
                    if(TextUtils.isEmpty(name.getText().toString()) || TextUtils.isEmpty(phone.getText().toString())
                    || TextUtils.isEmpty(addressDetail.getText().toString())
                    || TextUtils.isEmpty(addressRegionTv.getText().toString())) {
                        ToastUtils.showToast("请完整输入信息");
                    } else {
                        addNewAddress();
                    }
                } else {
                    if(addressId > -1) {
                        //修改收货地址
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    private void getAddressInfoById() {
        LoginUserInfo loginUserInfo = BaseApplication.getLoginUserInfo();
        if (null == loginUserInfo || !ZyUtils.getInstance().isNetConnected()) {
            return;
        }
        /*RequestParams httpParams = new RequestParams();
        httpParams.put("id", addressId);*/

        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/getAddressDetail/" + addressId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "getAddressInfoById onFailure responseString = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "getAddressInfoById onSuccess responseString = " + responseString);

                AddressDetailResp resp = new Gson().fromJson(responseString, AddressDetailResp.class);
                if(resp != null && resp.getCode() == 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            name.setText(resp.getData().getUserName());
                            phone.setText(resp.getData().getPhone());
                            addressDetail.setText(resp.getData().getAddress());
                            addressRegionTv.setText("");
                        }
                    });
                }
            }
        });

    }

    /**
     * 新增收货地址
     */
    private void addNewAddress() {
        LoginUserInfo loginUserInfo = BaseApplication.getLoginUserInfo();
        if (null == loginUserInfo || !ZyUtils.getInstance().isNetConnected()) {
            return;
        }
        JSONObject addressReq = new JSONObject();
        try {
            String address = deleteString2(addressRegionTv.getText() + addressDetail.getText().toString(), '/').replaceAll(" ", "");
            addressReq.put("address", address);
            addressReq.put("phone", phone.getText());
            addressReq.put("userName", name.getText());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        AsyncHttpUtils.getInstance().postJson(this, SERVICE_DOMAIN + "/appApi/addressAdd", addressReq, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "addNewAddress onSuccess responseString = " + responseString);
                try {
                    JSONObject object = new JSONObject(responseString);
                    if(object.has("code")) {
                        if(object.getInt("code") == 200) {
                            ToastUtils.showToast("地址添加成功");
                            AddressDetailActivity.this.finish();
                        } else {
                            ToastUtils.showToast(object.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }


    private void modifyAddress() {
        /*AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/appApi/addressAdd", new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "getAddressInfoById onFailure responseString = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "getAddressInfoById onSuccess responseString = " + responseString);

                AddressDetailResp resp = new Gson().fromJson(responseString, AddressDetailResp.class);
                if(resp != null && resp.getCode() == 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            name.setText(resp.getData().getUserName());
                            phone.setText(resp.getData().getPhone());
                            addressDetail.setText(resp.getData().getAddress());
                            addressRegionTv.setText("");
                        }
                    });
                }
            }
        });*/
    }


    private void doSelectRegion() {
        AddressRegionSelectUtils.getInstance().showRegionSelect(this, new AddressRegionSelectUtils.OnRegionSelect() {
            @Override
            public void onSelect(String result) {
                addressRegionTv.setText(result);
                //updateUserInfo("areaName", result);
            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * 删除指定字符方法
     * @param str
     * @param delChar
     * @return
     */
    public static String deleteString2(String str, char delChar) {
        StringBuffer stringBuffer = new StringBuffer("");
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != delChar) {
                stringBuffer.append(str.charAt(i));
            }
        }
        return stringBuffer.toString();
    }
}
